package com.easy.base.api.service.impl;

import java.util.Arrays;
import java.util.Optional;

import com.easy.base.api.model.entity.BaseEntity;
import com.easy.base.api.model.enums.ShowType;
import com.easy.base.api.model.exception.BizException;
import com.easy.base.api.service.IService;
import com.easy.base.api.utils.JpaUtil;

import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.http.HttpStatus;

public class BaseService<E extends BaseEntity, JPA extends JpaRepository<E, String>> implements IService<E> {

    @Autowired
    @SuppressWarnings("all")
    public JPA jpa;

    @Override
    public E insertEntity(E entity) {
        if (entity == null) {
            throw new BizException(HttpStatus.METHOD_NOT_ALLOWED, true, "请求参数不能为空",
                    ShowType.MessageWarn);
        }
        E e = jpa.save(entity);
        return e;
    }

    @Override
    public E updateEntity(E entity) {
        if (entity == null || Strings.isBlank(entity.getId())) {
            throw new BizException(HttpStatus.METHOD_NOT_ALLOWED, true, "ID不能为空", ShowType.MessageWarn);
        }
        Optional<E> optional = jpa.findById(entity.getId());
        if (optional.isPresent()) {
            JpaUtil.CopyNotNullProperties(entity, optional.get());
            E e = jpa.saveAndFlush(optional.get());
            return e;
        }
        throw new BizException(HttpStatus.NOT_FOUND, true, "所更新的数据不存在", ShowType.MessageWarn);
    }

    @Override
    public void removeEntity(String id) {
        if (Strings.isBlank(id)) {
            throw new BizException(HttpStatus.METHOD_NOT_ALLOWED, true, "ID不能为空", ShowType.MessageWarn);
        }
        jpa.deleteById(id);
    }

    @Override
    public void removeEntity(String[] ids) {
        if (ids.length == 0) {
            throw new BizException(HttpStatus.METHOD_NOT_ALLOWED, true, "ID清单不能为空",
                    ShowType.MessageWarn);
        }
        jpa.deleteAllById(Arrays.asList(ids));
    }

    @Override
    public Page<E> selectEntities(E model) {
        Page<E> pages = jpa.findAll(PageRequest.of(model.getCurrent() - 1, model.getPageSize()));
        return pages;
    }

    @Override
    public E selectEntityByID(String id) {
        if (Strings.isBlank(id)) {
            throw new BizException(HttpStatus.METHOD_NOT_ALLOWED, true, "ID不能为空", ShowType.MessageWarn);
        }
        return jpa.getById(id);
    }

}
